#pragma once

#include <iostream>
#include"ERRNO.hpp"
#include <sys/types.h>
#include <sys/socket.h>
#include<arpa/inet.h>
#include<string>
#include<cstdlib>
#include<functional>
#include <unistd.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<cstring>
#include"loghandler.hpp"
using namespace std;


void handler(int sock,uint16_t port,string ip)
{
    //简单添加字段就发回去
    struct sockaddr_in client;
    client.sin_family=AF_INET;
    client.sin_addr.s_addr = inet_addr(ip.c_str());
    client.sin_port=htons(port);
    socklen_t clientlen=sizeof client;
    //读取消息我们当前可以直接使用read ，后面会详细讲tcp的读取的问题
    char buffer[1024];
    while(1)
    {
        memset(buffer,0,sizeof buffer);
        int n =read(sock,buffer,sizeof buffer -1); //还是读取进来当字符串处理
        if(n>0) //说明读到了数据
        {
            buffer[n]=0;
            cout<<"receive a msg : "<<buffer<<endl;
            string msg ="response : ";
            msg+=buffer;
            int n =sendto(sock,msg.c_str(),msg.size(),0,(struct sockaddr*)&client,sizeof client);
            if(n==-1)
            {
                // cerr<<"sendto error"<<endl;
                logmessage(FATAL,"sendto fail");
                exit(SEND_ERR);
            }
        }
        else if(n==0) //说明对方关闭了文件描述符
        break;
        else
        {
            // cerr<<"read error"<<endl;
            logmessage(FATAL,"read error");
            exit(READ_ERR);
        }
    }
}


class ThreadData
{
    public:
    ThreadData(int sock,uint16_t clientport,string clientip)
    :_sock(sock),_clientport(clientport),_clientip(clientip)
    {}
    public:
    int _sock;
    uint16_t _clientport;
    string _clientip;
};

void* start_routine(void* arg)
{
    ThreadData* pdata = static_cast<ThreadData*>(arg);
    int sock = pdata->_sock;
    uint16_t port = pdata->_clientport;
    string ip = pdata->_clientip;
    handler(sock,port,ip); //调用业务逻辑
    close(sock);
    return nullptr;
}

